<!-- 页面名称 -->
<template>
  <div>
    <div class="can-drag-pic-list">
      <div class="vt pic-item" v-for="(pic, idx) in picList" :key="idx">
        <zm-image-upload v-if="picLoading" v-model="pic.url" :limit="1" :accept="accept" @on-success="updSuccess" @on-remove="updRemove(idx)" :single-file-size="singleFileSize"></zm-image-upload>
        <i v-if="picList && picList.length > 2 && pic.url && pic.url !== ''" class="el-icon-rank primary fs22 pointer drag-handle"></i>
      </div>
    </div>
  </div>
</template>
<script>
import { ZmImageUpload } from '../ZmUpload'
import Sortable from 'sortablejs'

export default {
  name: 'DragImageUpload',
  components: {
    ZmImageUpload
  },
  props: {
    value: { // 双向绑定字符串
      type: String,
      default: ''
    },
    max: { // 最大上传数
      type: Number,
      default: 1
    },
    accept: { // 可接收文件格式
      type: String,
      default: '.jpg,.JPG,.jpeg,.JPEG,.png,.PNG'
    },
    singleFileSize: { // 单个文件大小限制（单位Mb）
      type: Number,
      default: 0.5
    }
  },
  data () {
    return {
      sortable: null,
      picList: [{
        url: ''
      }],
      picLoading: true
    }
  },
  watch: {
    value (val) {
      if (val) {
        const valueList = val.split(',').filter(i => i)
        if (valueList.length < this.max) {
          valueList.push('')
        }
        const picTempList = valueList.map(i => {
          return {
            url: i
          }
        })
        this.picList = JSON.parse(JSON.stringify(picTempList))
      }
    },
    picList (val) {
      const urlList = this.picList.map(i => {
        if (i.url && i.url !== '') {
          return i.url
        }
      })
      this.$emit('after-change')
      this.$emit('input', urlList.join(','))
    }
  },
  created () { },
  mounted () {
    if (this.value) {
      const valueList = this.value.split(',').filter(i => i)
      if (valueList.length < this.max) {
        valueList.push('')
      }
      const picTempList = valueList.map(i => {
        return {
          url: i
        }
      })
      this.picList = JSON.parse(JSON.stringify(picTempList))
    }
    this.setSort()
  },
  methods: {
    // 上传成功回调
    updSuccess () {
      this.picLoading = false
      if (this.picList.length < this.max) {
        this.picList.push({
          url: ''
        })
      }
      if (this.picList.length === this.max) {
        const urlList = this.picList.map(i => {
          if (i.url && i.url !== '') {
            return i.url
          }
        })
        this.$emit('after-change')
        this.$emit('input', urlList.join(','))
      }
      this.$nextTick(() => {
        this.picLoading = true
      })
    },

    // 删除图片回调
    updRemove (idx) {
      if (this.picList.length > 1) {
        this.picList.splice(idx, 1)
      }
      this.picLoading = true
    },

    // 拖拽
    setSort () {
      if (this.sortable && !this.more) return

      this.$nextTick(() => {
        const el = document.querySelectorAll(
          '.can-drag-pic-list'
        )[0]
        const that = this

        this.sortable = Sortable.create(el, {
          draggable: '.pic-item',
          ghostClass: 'sortable-ghost',
          handle: '.drag-handle',
          setData: function (dataTransfer) {
            dataTransfer.setData('Text', '')
          },
          onEnd: async evt => {
            const nIndex = evt.newIndex
            const oIndex = evt.oldIndex
            if (nIndex === oIndex) return
            const $li = el.children[nIndex]
            const $oldLi = el.children[oIndex]
            el.removeChild($li)
            if (nIndex > oIndex) {
              el.insertBefore($li, $oldLi)
            } else {
              el.insertBefore($li, $oldLi.nextSibling)
            }

            const oldList = that.picList
            const listTemp = oldList.slice(0)
            const targetRow = listTemp.splice(oIndex, 1)[0]
            that.picLoading = fals
            // that.picList.splice(oIndex, 1)[0]
            that.picList.splice(nIndex, 0, targetRow)
            that.$nextTick(() => {
              that.picLoading = true
            })
          }
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.can-drag-pic-list {
  .pic-item {
    position: relative;
    margin-right: 5px;
    .drag-handle {
      position: absolute;
      top: -5px;
      left: -5px;
    }
  }
}
</style>
